<?php

require_once 'BluesCoders/Event/Listener.php';

/**
 * Description of Front
 *
 * @author miho
 */
class BluesCoders_Controller_Front {

    protected $_requestFactory;
    protected $_responseFactory;
    protected $_dispatcherMapper;

    public function setRequestFactory($value) {
        $this->_requestFactory = $value;
    }

    public function setResponseFactory($value) {
        $this->_responseFactory = $value;
    }

    public function setDispatcherMapper($value) {
        $this->_dispatcherMapper = $value;
    }

    public function  __construct() {
        BluesCoders_Event_Dispatcher::getIsntance()->addEventListener(
            BluesCoders_Application_Event::START_UP,
            new BluesCoders_Event_Listener($this, 'applicationStartUpHandler')
        );
    }

    public function applicationStartUpHandler(BluesCoders_Application_Event $event) {
        echo 'Starting up BluesCoders_Controller_Front';

        $request = $this->_requestFactory->getRequest();
        $response = $this->_responseFactory->getResponse();

        $dispatcherId = $this->_dispatcherMapper->getDispatcher($request);

        try{
            $dispatcher = $event->getApplication()->getContext()->getBean($dispatcherId);
            $viewResolver = $event->getApplication()->getContext()->getBean('viewResolver');
        }catch(Exception $e) {
            throw new Exception('Getting of dispatcher failed. nested exception is: '.$e->getMessage());
        }

        $dispatcher->initializeContext($event->getApplication()->getContext());

        $result = $dispatcher->dispatch($request, $response);
        if(is_string($result)){
            $view = $viewResolver->getView($result);
            $response->appendString($view->render());
        }

        $response->flush();
        return true;
    }

    public function getDispatcher($request) {
        
    }


}
?>
